package com.michael.doubanonline;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.alibaba.fastjson.JSON;
import com.michael.doubanonline.OnlineDetailAdapter.OnPictureClick;
import com.michael.doubanonline.base.ShareActionBarActivity;
import com.michael.doubanonline.bean.Photo;
import com.michael.doubanonline.bean.PhotoList;
import com.michael.doubanonline.component.PullToRefreshListViewWithFooter;
import com.michael.doubanonline.component.PullToRefreshListViewWithFooter.OnFooterListViewLastItemVisibleListener;
import com.michael.doubanonline.component.PullToRefreshListViewWithFooter.OnFooterListViewRefreshListener;
import com.michael.doubanonline.dialog.DialogUtil;
import com.michael.doubanonline.http.InterfaceLib;
import com.michael.doubanonline.http.RequestTask;
import com.michael.doubanonline.http.RequestTask.OnTaskResultListener;
import com.michael.doubanonline.util.ToastUtil;

/**
 * 从主界面跳转进来的线上活动详细界面
 * 
 * */
public class OnlineDetailActivity extends ShareActionBarActivity implements ActionBar.OnNavigationListener
{

	/** 接收传递进来的线上活动的ID，ID为String类型 */
	public static final String INTENT_KEY_ID = "INTENT_KEY_ID";
	/** 接收传递进来的线上活动的标题 */
	public static final String INTENT_KEY_TITLE = "INTENT_KEY_TITLE";
	/** 接收传递进来的线上活动的内容简介 */
	public static final String INTENT_KEY_DETAIL = "INTENT_KEY_DETAIL";
	/** 具有下来刷新和显示更多功能的ListView */
	private PullToRefreshListViewWithFooter lvImages;
	/** 数据源适配器 */
	private OnlineDetailAdapter adapter;
	/** 存放照片数据源的ArrayList */
	private ArrayList<Photo> dataList;
	/** 当前线上活动的id */
	public static String id;
	/** 所有图片的数量 */
	private int totalPhotoCount;
	/** 分类 */
	private String sortBy;
	/** 每页请求的数据 */
	public static int PAGE_SIZE = 40;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);

		setActionBar();
		iniComponent();
		iniListViewHeader();
		iniListener();
		lvImages.setAdapter(adapter);
		id = this.getIntent().getStringExtra(INTENT_KEY_ID);
	}

	private void iniComponent()
	{
		sortBy = InterfaceLib.GetPhotos.SORT_BY_TIME;// 默认按时间排序
		lvImages = (PullToRefreshListViewWithFooter) findViewById(R.id.lvList);
		dataList = new ArrayList<Photo>();
		adapter = new OnlineDetailAdapter(this, dataList);
		adapter.setOnPictureClick(new OnPictureClick()
		{

			@Override
			public void onClick(int position)
			{
				Intent intent = new Intent(OnlineDetailActivity.this, PhotoDetailActivity.class);
				intent.putExtra(PhotoDetailActivity.INTENT_KEY_TOTAL, totalPhotoCount);
				intent.putExtra(PhotoDetailActivity.INTENT_KEY_PHOTO_POSITION, position);
				intent.putExtra(PhotoDetailActivity.INTENT_KEY_ID, OnlineDetailActivity.id);
				intent.putExtra(PhotoDetailActivity.INTENT_KEY_DATA_LIST, dataList);
				intent.putExtra(PhotoDetailActivity.INTENT_KEY_SORT_BY, sortBy);
				startActivity(intent);
			}
		});
	}

	private void iniListener()
	{

		// 下拉刷新
		lvImages.setOnFooterListViewRefreshListener(new OnFooterListViewRefreshListener()
		{

			@Override
			public void onFooterListViewRefresh()
			{
				requestData(true);
			}
		});

		// 显示更多
		lvImages.setOnFooterListViewLastItemVisibleListener(new OnFooterListViewLastItemVisibleListener()
		{

			@Override
			public void onFooterListViewLastItemVisible()
			{
				if (dataList.size() == totalPhotoCount)
				{
					lvImages.setListViewFooterContent(PullToRefreshListViewWithFooter.LOADING_STATE_DONE, "全部加载完毕了哦~");
				} else
				{
					requestData(false);
				}
			}
		});
	}

	/**
	 * 设置头部
	 * 
	 * */
	private void setActionBar()
	{

		ActionBar actionBar = getSupportActionBar();
		Context context = actionBar.getThemedContext();
		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.detail_titles, R.layout.sherlock_spinner_item);
		list.setDropDownViewResource(R.layout.list_action_bar_item);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		actionBar.setListNavigationCallbacks(list, this);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME);
		actionBar.setIcon(this.getResources().getDrawable(R.drawable.ic_launcher));
		actionBar.setDisplayHomeAsUpEnabled(true);// 让icon可以点击，并在icon的右边加上一个<箭头在onMenuItemSelected方法中被监听
		actionBar.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.action_bar_bg));
		actionBar.setDisplayShowCustomEnabled(true);
		// 小菊花：）
//		LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		View view = layoutInflater.inflate(R.layout.layout_actionbar_progressbar, null);
//		actionBar.setCustomView(view, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER));
	}

	/**
	 * 将Json解析为Bean
	 * */
	private PhotoList resolveJsonToBean(String jsonString)
	{
		return JSON.parseObject(jsonString, PhotoList.class);
	}
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		if(requestPhotoList != null)
		{
			requestPhotoList.cancelRequest();
		}
	}

	private RequestTask requestPhotoList;
	
	/**
	 * 获取数据
	 * 
	 * */
	private void requestData(final boolean isClear)
	{
	    requestPhotoList = new RequestTask(this, "获取图片列表");
		requestPhotoList.setOnTaskResultListener2(new OnTaskResultListener()
		{
			@Override
			public void onStart()
			{
				setRefreshState(true);
				lvImages.setListViewFooterContent(PullToRefreshListViewWithFooter.LOADING_STATE_LOADING);
			}

			@Override
			public void onSuccess(String jsonResponse)
			{
				if (jsonResponse != null)
				{
					PhotoList photos = resolveJsonToBean(jsonResponse);
					if (photos != null)
					{
						totalPhotoCount = Integer.parseInt(photos.getTotal());
						updateListView(photos, isClear);
					} else
					{
						ToastUtil.show("数据解析失败");
					}
				} else
				{
					ToastUtil.show("获取数据为空");
				}
				lvImages.setListViewFooterContent(PullToRefreshListViewWithFooter.LOADING_STATE_DONE);
			}

			@Override
			public void onFail(String message)
			{
				lvImages.setListViewFooterContent(PullToRefreshListViewWithFooter.LOADING_STATE_FAIL);
			}

			@Override
			public void onFinish()
			{
				lvImages.onRefreshComplete();
				setRefreshState(false);
			}

		});
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(InterfaceLib.GetPhotos.start, getStart(isClear) + "");
		map.put(InterfaceLib.GetPhotos.count, PAGE_SIZE + "");
		map.put(InterfaceLib.GetPhotos.sortby, sortBy);
		requestPhotoList.request("online/" + id + "/" + InterfaceLib.GetPhotos.apiActionName, map);
	}

	/**
	 * 更新ListView
	 * 
	 * @param onlines
	 *            数据源
	 * @param isClear
	 *            是否清空旧数据
	 */
	private void updateListView(PhotoList photoList, boolean isClear)
	{
		if (isClear)
		{
			dataList.clear();
		}
		dataList.addAll(photoList.getPhotos());
		adapter.notifyDataSetChanged();
		lvImages.setFooterViewVisibility(View.VISIBLE);
	}

	/**
	 * 获取当前需要从哪一个开始下载
	 * */
	private int getStart(boolean isClear)
	{
		if (dataList == null || dataList.size() == 0 || isClear)
		{
			return 0;
		}
		return dataList.size();
	}

	/**
	 * 初始化ListView的Header
	 * */
	private void iniListViewHeader()
	{
		LayoutInflater layoutInflater = this.getLayoutInflater();
		View headerView = (View) layoutInflater.inflate(R.layout.list_header_detail, lvImages.getRefreshableView(), false);
		TextView tvTitle = (TextView) headerView.findViewById(R.id.tv_title);
		TextView tvDetail = (TextView) headerView.findViewById(R.id.tv_detail);
		tvTitle.setClickable(true);
		RelativeLayout rlDetail = (RelativeLayout) headerView.findViewById(R.id.rl_detail);
		rlDetail.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				showDescDialog();
			}
		});
		tvTitle.setText(this.getIntent().getStringExtra(INTENT_KEY_TITLE));
		tvDetail.setText(this.getIntent().getStringExtra(INTENT_KEY_DETAIL));
		lvImages.getRefreshableView().addHeaderView(headerView);
	}

	/**
	 * 处理导航项的点击事件 默认就会进行调用
	 * 
	 * */
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId)
	{

		switch (itemPosition)
		{
		case 0:// 按时间排序
			sortBy = InterfaceLib.GetPhotos.SORT_BY_TIME;
			requestData(true);
			break;
		case 1:// 按热度排序
			sortBy = InterfaceLib.GetPhotos.SORT_BY_VOTE;
			requestData(true);
			break;
		case 2:// 按评论排序
			sortBy = InterfaceLib.GetPhotos.SORT_BY_COMMENT;
			requestData(true);
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * 根据Intent传递进来的title和detail内容显示对话框
	 * */
	private void showDescDialog()
	{

		Intent intent = getIntent();
		String title = intent.getStringExtra(INTENT_KEY_TITLE);
		String message = intent.getStringExtra(INTENT_KEY_DETAIL);
		DialogUtil.show(this, title, message);
	}

}
